var network = require('../utils/network_util.js');
var api = require('../utils/api.js');
var count = 0;

function getBaseInfo(app) {
  // 登录
  wx.login({
    success: function (res) {
      // 发送 res.code 到后台换取 openId, sessionKey, unionId
      app.globalData.jsCode = res.code;
      if (wx.getExtConfig) {
        wx.getExtConfig({
          success: function (res) {
            //console.log(res.extConfig)
            console.log('----------jsCode----------')
            console.log(app.globalData.jsCode)
            // 得到appId
            app.globalData.appId = res.extConfig.appId
            app.globalData.tenantId = res.extConfig.tenantId;
            network._post1(app, api.wxUrl, { appId: app.globalData.appId, jsCode: app.globalData.jsCode }, openIdSuccess, fail);
          }
        })
      }
    },
    fail: function (res) {
      console.log("微信登录失败")
      console.log(res)
      network._error(api.wxError, res);
    }
  })
}

// 返回openId请求结果
var openIdSuccess = function (that, res) {
  console.log(res)
  // 得到openId
  that.globalData.openId = res.data.data.openid
  that.globalData.sessionKey = res.data.data.session_key

  network._post_json(that, api.getUserInfo, { appId: that.globalData.appId, openId: that.globalData.openId }, userAndTenantInfoSuccess);
}

// 返回openId请求失败结果
var fail = function (that, res) {
  console.log("服务器连接失败")
  console.log(res)
  network._error(api.wxError, res);
  count++;
  if (count < 3) {
    network._post1(that, api.wxUrl, { appId: that.globalData.appId, jsCode: that.globalData.jsCode }, openIdSuccess, fail);
  }
}

// 获取个人及商家信息结果
var userAndTenantInfoSuccess = function (that, res) {
  if (res.data.data) {
    var userAndTenantInfo = res.data.data;
    that.globalData.userAndTenantInfo = userAndTenantInfo;
    that.globalData.userId = userAndTenantInfo.id;

    if (that.userAndTenantInfoCallback) {
      that.userAndTenantInfoCallback(userAndTenantInfo)
    }

    // 获取用户信息
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: function (res) {
              // 可以将 res 发送给后台解码出 unionId
              console.log(res)
              that.globalData.userInfo = res.userInfo
              network._post_json(that, api.modifyUserInfo, { nickName: res.userInfo.nickName, avatarUrl: res.userInfo.avatarUrl, gender: that.globalData.userInfo.gender }, modifySuccess);
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (that.userInfoReadyCallback) {
                that.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })

  }
}

var modifySuccess = function (that, res) {

}


module.exports = {
  getBaseInfo: getBaseInfo
}
